#!/usr/bin/perl

######################################################################
package Swignition::PoxParser;
######################################################################

use utf8;
use strict;

use Swignition::GenericParser;
use vars qw(@ISA);
@ISA = qw(Swignition::GenericParser);

sub new
{
	my $class    = shift;
	my $source   = shift;
	my $opts     = shift;
	my $this     = Swignition::GenericParser::object_structure($source, $opts);
	
	bless $this, $class;	
	
	$this->build_dom_tree;
	$this->find_base_uri;
	
	if ($this->{options}->{p_AUTO})
	{
		$this->{RDF}->{ $this->uri } = Swignition::RDFModel::Subject->new($this->uri);	

		if ($this->{DOM}->documentElement->tagName eq 'TriX')
		{
			Swignition::GenericParser::RDF::handle_trix(
				$this, $this->{SOURCE}, $this->uri, 'trix', 'RDF', $this->{DOM});
		}
		
		else
		{
			Swignition::GenericParser::GRDDL::consume($this)
				if Swignition::GenericParser::GRDDL::is_enabled($this);
		}
		
		Swignition::GenericParser::HTTP::consume($this)
			if Swignition::GenericParser::HTTP::is_enabled($this);

		Swignition::GenericParser::Recursive::consume($this)
			if Swignition::GenericParser::HTTP::is_enabled($this);

		$this->smush;
	}

	return $this;	
}

sub build_dom_tree
{
	my $this = shift;

	# XML::LibXML parser.
	$Swignition::GenericParser::XDP = XML::LibXML->new();
	
	# Attempt to parse.
	eval {
		$this->{DOM} = $Swignition::GenericParser::XDP->parse_string($this->{Source});
	};
	
	# If parsing failed, then 
	if (! $this->{DOM} )
	{
		$this->{_raw_source} = $this->{Source};
		
		# Figure out encoding.
		my $enc = 'iso-8859-1';
		if (($this->{RESPONSE} && $this->{RESPONSE}->header('content-type') =~ /\bcharset=[\"\'\s]?([a-z0-9-]+)/i)
		|| substr($this->{Source},0,2048) =~ /\bencoding=[\"\'\s]?([a-z0-9-]+)/i 
		|| substr($this->{Source},0,2048) =~ /\bcharset=[\"\'\s]?([a-z0-9-]+)/i )
			{ $enc = lc($1); }
		
		# Decode into UTF-8.
		if ($enc ne 'utf-8')
		{
			$this->{decoded_from} = $enc;
			$this->{Source} = decode($enc, $this->{Source});
		}

		# Try parsing again.
		if (!eval {
			$this->{DOM} = $Swignition::GenericParser::XDP->parse_string($this->{Source});
		})
		
		# If it still fails, then
		{
			print "COULD NOT PARSE!\n";
			die;
		}
	}	
}




1;
